<template>
    <div class="white-box">
        <base-steps :arrs="stepArr" :active="stepActive"></base-steps>
        <p class="step-h3">{{ stepArr[stepActive].text }}<span v-if="stepActive == 2">（图片建议尺寸：宽度750px及以下，高度1000px及以下）</span></p>
        <!-- 第一步-基本信息 -->
        <div v-show="stepActive == 0">
            <el-form ref="ruleOneRef" :model="ruleOneForm" :rules="ruleOneCheck" label-width="140px">
                <el-form-item label="供应商" prop="supplier_name">
                    <el-input
                        v-model.trim="ruleOneForm.supplier_name"
                        readonly
                        :suffix-icon="ArrowRight"
                        placeholder="请选择供应商"
                        clearable
                        @click="dialogSupplier = true"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="选择商品" prop="comm_id" required>
                    <div class="img-box flexs-center" @click.stop="dialogGoods = true" v-if="ruleOneForm.comm_id == ''">
                        <el-icon color="#999" size="26px">
                            <Plus />
                        </el-icon>
                    </div>
                    <div class="img-selects" v-else>
                        <el-image class="img-selects__pic" :src="proxy.imgUrl + goodObj.product_img + '!img_400'" fit="cover" />
                        <div class="img-del" @click.stop="delGood">
                            <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                        </div>
                    </div>
                    <div class="input-tips">请先选择供应商，再来选择商品</div>
                </el-form-item>
                <el-form-item label="商品主图" prop="img_paths" required>
                    <draggable
                        v-model="ruleOneForm.img_paths"
                        item-key="item"
                        animation="200"
                        style="display: flex; flex-flow: row wrap; flex: none"
                        v-if="ruleOneForm.img_paths.length > 0"
                    >
                        <template #item="{ element, index }">
                            <div class="img-list">
                                <div class="img-selects">
                                    <el-image class="img-selects__pic" :src="proxy.imgUrl + element + '!img_400'" :preview-src-list="srcList" fit="cover" />
                                    <div class="img-del" @click.stop="delImg(index)">
                                        <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </draggable>
                    <div class="img-box flexs-center" @click.stop="showImg = true">
                        <el-icon color="#999" size="26px">
                            <UploadFilled />
                        </el-icon>
                    </div>
                    <div class="input-tips">
                        图片尺寸建议750px * 750px（保持正方形模式）， 默认第一张为主图(可拖动排序)，图片可批量选择，建议主图不超过<code>6</code>张
                    </div>
                </el-form-item>
                <el-form-item label="商品视频">
                    <div class="video-box" v-if="videoList.length > 0">
                        <video :src="proxy.imgUrl + videoList[0]" controls controlsList="nodownload"></video>
                        <div class="video-del" @click.stop="delVideo">
                            <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                        </div>
                    </div>
                    <el-upload
                        ref="uploadRef"
                        accept=".mp4"
                        v-loading="videoLoading"
                        class="prize-upload"
                        :action="actionUrl()"
                        :http-request="uploadVideo"
                        list-type="picture-card"
                        :on-remove="handleRemove"
                        :on-exceed="handleExceed"
                        :before-upload="beforeAvatarUpload"
                        :on-change="fileChange"
                        :limit="1"
                        v-else
                    >
                        <el-icon color="#999">
                            <upload-filled />
                        </el-icon>
                    </el-upload>
                    <div class="input-tips">为了更好的设备兼容，目前视频仅支持上传<code>.mp4</code>格式</div>
                </el-form-item>
                <!-- <el-form-item label="标签设置" prop="tag_radio_type">
                <el-radio-group v-model="ruleOneForm.tag_radio_type">
                    <el-radio :label="item.type" v-for="item in tags" :key="item.type">{{ item.names }}</el-radio>
                </el-radio-group>
            </el-form-item> -->
                <el-form-item label="商品等级" prop="level_id">
                    <el-select v-model="ruleOneForm.level_id" clearable placeholder="请选择商品等级">
                        <el-option :label="item.level_name" :value="item.level_id" v-for="item in leave_list" :key="item.level_id" />
                    </el-select>
                    <div class="input-tips">请先选择商品，然后再来选择商品等级</div>
                </el-form-item>
                <el-form-item label="商品属性" prop="good_attr_name">
                    <el-input
                        v-model.trim="ruleOneForm.good_attr_name"
                        readonly
                        :suffix-icon="ArrowRight"
                        placeholder="请选择商品属性"
                        clearable
                        @click="clickDrawAttr"
                    >
                    </el-input>
                    <div class="input-tips">请先选择商品，然后再来选择商品属性;设置后，用户可快速定位到该商品</div>
                </el-form-item>
            </el-form>
        </div>

        <!-- 第二步-扩展属性 -->
        <div v-show="stepActive == 1">
            <el-form ref="ruleTwoRef" :model="ruleTwoForm" :rules="ruleTwoCheck" label-width="140px">
                <el-form-item label="商品关键词" prop="keywords">
                    <el-input v-model.trim="ruleTwoForm.keywords" clearable placeholder="请输入关键词，关键词以英文逗号 “,” 隔开" />
                    <div class="input-tips">
                        用于关键词搜索商品，可添加多个关键词; 以英文状态下的逗号<code>,</code>隔开，末尾不需要带<code>,</code>例如：<code>商品,鲜花 </code>
                    </div>
                </el-form-item>
                <el-form-item label="商品编码" prop="codes">
                    <el-input v-model.trim="ruleTwoForm.codes" clearable placeholder="请输入商品编码" />
                </el-form-item>
                <el-form-item label="基础销量" prop="sale">
                    <el-input v-model.trim="ruleTwoForm.sale" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入销量" />
                    <div class="input-tips">设置后，您的用户看到的销量=基础销量+下单量</div>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input v-model.trim="ruleTwoForm.sort" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入排序" />
                    <div class="input-tips">一个好的排序能让您更加方便管理商品</div>
                </el-form-item>
                <el-form-item label="供应价" prop="supplier_price">
                    <el-input
                        v-model.trim="ruleTwoForm.supplier_price"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入供应价"
                        @input="inputPrice"
                    />
                    <span class="form-item__char">元</span>
                    <div class="input-tips">供应商的成本价格</div>
                </el-form-item>
                <el-form-item label="零售价" prop="price">
                    <el-input v-model.trim="ruleTwoForm.price" readonly clearable placeholder="零售价" />
                    <el-button class="form-item__btn" type="primary" :icon="Edit" @click="showLevel = !showLevel">编辑会员等级价格</el-button>
                    <div class="input-tips">
                        <code>零售价</code>是根据<code>供应价</code> + <code>涨跌价格</code>自动生成的，不能自定义零售价，右侧点击可编辑会员等级价格
                    </div>
                    <transition name="el-zoom-in-top" v-show="showLevel">
                        <div class="vip-price">
                            <div class="vip-level">
                                <div class="input-tips" style="margin-bottom: 20px">
                                    计算规则：<code>会员等级价</code> = <code>零售价</code> - <code>输入的价格</code>
                                </div>
                                <div class="vip-level__item" v-for="item in userLevel" :key="item.grade_id">
                                    <p class="vip-level__text">{{ item.level_name }}</p>
                                    <div class="vip-level__right">
                                        <el-icon color="#333" class="vip-level__right-icon"><Minus /></el-icon>
                                        <el-input
                                            v-model.trim="item.discount"
                                            oninput="value=value.replace(/[^\d.]/g,'')"
                                            placeholder="输入需要减少的价格"
                                            clearable
                                        />
                                        <span class="vip-level__right-unit">元</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </transition>
                </el-form-item>
                <el-form-item label="库存" prop="stock">
                    <el-input v-model.trim="ruleTwoForm.stock" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入库存" />
                </el-form-item>
                <!-- 非区域代理设置 -->
                <p class="step-h3" style="margin-top: 40px">非区域代理商推广佣金设置</p>
                <el-form-item label="非区域代理商返佣" prop="dls_rebate">
                    <el-radio-group v-model="ruleTwoForm.dls_rebate">
                        <el-radio label="1" size="large">开启</el-radio>
                        <el-radio label="0" size="large">关闭</el-radio>
                    </el-radio-group>
                    <div class="input-tips">关闭后，将不给非区域代理商返佣</div>
                </el-form-item>
                <el-form-item label="一级代理返佣比例" prop="large_group">
                    <el-input v-model.trim="ruleTwoForm.large_group" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入返佣比例" />
                    <span class="form-item__char">%</span>
                    <div class="input-tips">分给一级代理的返佣比例，这个比例包含二级代理和三级代理的返佣</div>
                </el-form-item>
                <el-form-item label="二级代理返佣比例" prop="middle_group">
                    <el-input v-model.trim="ruleTwoForm.middle_group" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入返佣比例" />
                    <span class="form-item__char">%</span>
                    <div class="input-tips">二级代理默认由一级代理去发展，这个比例包含三级代理的返佣</div>
                </el-form-item>
                <el-form-item label="三级代理返佣比例" prop="small_group">
                    <el-input v-model.trim="ruleTwoForm.small_group" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入返佣比例" />
                    <span class="form-item__char">%</span>
                    <div class="input-tips">三级代理默认由二级代理去发展</div>
                </el-form-item>
                <el-form-item label="一级平级返佣比例" prop="flat_level">
                    <el-input v-model.trim="ruleTwoForm.flat_level" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入返佣比例" />
                    <span class="form-item__char">%</span>
                    <div class="input-tips">一级平级/代理销售返佣比例</div>
                </el-form-item>
                <el-form-item label="二级平级返佣比例" prop="flat_level_two">
                    <el-input v-model.trim="ruleTwoForm.flat_level_two" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入返佣比例" />
                    <span class="form-item__char">%</span>
                    <div class="input-tips">二级平级/代理销售返佣比例</div>
                </el-form-item>
                <el-form-item label="三级平级返佣比例" prop="flat_level_three">
                    <el-input v-model.trim="ruleTwoForm.flat_level_three" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入返佣比例" />
                    <span class="form-item__char">%</span>
                    <div class="input-tips">三级平级/代理销售返佣比例</div>
                </el-form-item>
                <el-form-item label="越级返佣比例" prop="exceed_level">
                    <el-input v-model.trim="ruleTwoForm.exceed_level" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入返佣比例" />
                    <span class="form-item__char">%</span>
                </el-form-item>
                <!-- 区域代理设置 -->
                <p class="step-h3" style="margin-top: 40px">区域代理商推广佣金设置</p>
                <el-form-item label="区域代理商返佣" prop="dls_area_rebate">
                    <el-radio-group v-model="ruleTwoForm.dls_area_rebate">
                        <el-radio label="1" size="large">开启</el-radio>
                        <el-radio label="0" size="large">关闭</el-radio>
                    </el-radio-group>
                    <div class="input-tips">关闭后，将不给区域代理商返佣</div>
                </el-form-item>
                <el-form-item label="省级返佣比例" prop="pro_area">
                    <el-input v-model.trim="ruleTwoForm.pro_area" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入省级返佣比例" />
                    <span class="form-item__char">%</span>
                    <div class="input-tips">分给省级的返佣比例，这个比例包含市级代理和县级代理的返佣</div>
                </el-form-item>
                <el-form-item label="市级返佣比例" prop="city_area">
                    <el-input v-model.trim="ruleTwoForm.city_area" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入市级返佣比例" />
                    <span class="form-item__char">%</span>
                    <div class="input-tips">市级默认由省级代理去发展，这个比例包含县级代理的返佣</div>
                </el-form-item>
                <el-form-item label="县级代理返佣比例" prop="district_area">
                    <el-input v-model.trim="ruleTwoForm.district_area" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入县级返佣比例" />
                    <span class="form-item__char">%</span>
                    <div class="input-tips">县级代理默认由市级代理去发展</div>
                </el-form-item>
            </el-form>
        </div>

        <!-- 第三步-商品详情 -->
        <div v-show="stepActive == 2">
            <div class="editor-box">
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
                <Editor style="height: 440px; overflow-y: hidden" v-model="valueHtml" :defaultConfig="editorConfig" mode="default" @onCreated="handleCreated" />
            </div>
        </div>

        <!-- 固定底部按钮 -->
        <div class="foot-btn flexs-center" style="margin-top: 30px">
            <el-button type="default" plain @click="clickCancel">取消</el-button>
            <el-button type="default" plain @click="clickPrev" v-if="stepActive > 0">上一步</el-button>
            <el-button type="primary" @click="stepActive == 0 ? submitOneForm(ruleOneRef) : submitTwoForm(ruleTwoRef)" v-if="stepActive < 2">
                下一步
            </el-button>
            <el-button type="primary" :loading="form_loading" @click="handleConfirm" v-if="stepActive == 2">确认保存</el-button>
        </div>

        <!-- 商品列表 -->
        <el-dialog v-model="dialogGoods" :append-to-body="true" :destroy-on-close="true" title="商品列表" width="860px" top="10vh" @close="closeGoods">
            <div class="task-one" style="margin-top: 0">
                <div class="task-one__item">
                    <el-input placeholder="请输入商品名称" v-model="good_name" @keyup.enter.native="goodSearch" clearable></el-input>
                </div>
                <div class="task-one__item">
                    <el-button type="primary" :loading="search_btn" :icon="Search" @click="goodSearch">搜索</el-button>
                </div>
            </div>
            <el-table
                class="table-mb"
                :data="goods"
                :header-cell-style="{ background: '#F5F7FA' }"
                element-loading-background="rgba(255, 255, 255, 0.6)"
                v-loading="table_loading"
            >
                <el-table-column prop="product_common_id" label="商品ID" width="90" fixed="left"></el-table-column>
                <el-table-column label="商品名称" min-width="200" fixed="left">
                    <template #default="{ row }">
                        <div class="table-lr">
                            <el-image class="table-lr__img" :src="proxy.imgUrl + row.product_img + '!img_400'" fit="cover" v-if="row.product_img" />
                            <div class="table-lr__right line-two">
                                <p>{{ row.product_name }}</p>
                                <p>颜色：{{ row.color }}</p>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="cate_title" label="分类" width="120"></el-table-column>
                <el-table-column label="等级" width="100">
                    <template #default="{ row }">
                        <p v-if="row.product_levels.length > 0">
                            <span v-for="(item, index) in row.product_levels" :key="item.level_id"
                                >{{ item.level_name }}<em v-if="index != row.product_levels.length - 1">,</em></span
                            >
                        </p>
                    </template>
                </el-table-column>
                <el-table-column label="规格" width="120">
                    <template #default="{ row }">
                        <p>{{ row.norm }}/{{ row.unit }}</p>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="90" fixed="right">
                    <template #default="{ row }">
                        <el-button color="#4B93FA" style="color: #fff" @click.stop="selectGoods(row)">选择</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background v-model:current-page="good_page" :page-size="6" :total="good_total" layout="total, prev, pager, next, jumper">
            </el-pagination>
        </el-dialog>

        <!-- 商品属性 -->
        <el-drawer title="选择商品属性" v-model="drawerAttr" direction="rtl" size="640px" :append-to-body="true" :destroy-on-close="true" @close="closeDeawer">
            <div class="attr-box" v-for="item in attrs" :key="item.attr_id">
                <p class="attr-title">{{ item.attr_name }}</p>
                <div class="attr-sub">
                    <span
                        :class="[{ 'attr-active': sub.is_select }, 'attr-label']"
                        v-for="(sub, sub_index) in item.attr_value"
                        :key="sub.attr_value_id"
                        @click="clickAttr(item, sub_index, sub)"
                    >
                        {{ sub.attr_value_name }}
                    </span>
                </div>
            </div>
            <template #footer>
                <div class="drawer-footer flexs-center">
                    <el-button type="primary" @click="confirmAttr">确认选择</el-button>
                    <el-button @click="resetAttr">重置</el-button>
                </div>
            </template>
        </el-drawer>

        <!-- 供应商列表 -->
        <el-dialog v-model="dialogSupplier" :append-to-body="true" :destroy-on-close="true" title="供应商列表" width="600px" @close="closeSupp">
            <div class="task-one" style="margin-top: 0">
                <div class="task-one__item">
                    <el-input placeholder="请输入供应商名称" v-model="supp_name" @keyup.enter.native="suppSearch" clearable></el-input>
                </div>
                <div class="task-one__item">
                    <el-button type="primary" :loading="search_btn" :icon="Search" @click="suppSearch">搜索</el-button>
                </div>
            </div>
            <el-table
                class="table-mb"
                :data="suppliers"
                :header-cell-style="{ background: '#F5F7FA' }"
                element-loading-background="rgba(255, 255, 255, 0.6)"
                v-loading="table_loading"
            >
                <el-table-column prop="supplier_id" label="供应商ID" width="110"></el-table-column>
                <el-table-column label="供应商">
                    <template #default="{ row }">
                        <div class="table-lr">
                            <el-image class="table-lr__img supp-logo" loading="lazy" :src="proxy.imgUrl + row.logo + '!img_400'" fit="cover" v-if="row.logo" />
                            <div class="table-lr__right line-two" style="align-items: center; flex-direction: row">
                                {{ row.title }}
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                        <el-button color="#4B93FA" style="color: #fff" @click.stop="selectSupp(row)">选择</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background v-model:current-page="supp_page" :page-size="6" :total="supp_total" layout="total, prev, pager, next, jumper">
            </el-pagination>
        </el-dialog>

        <!-- 图片库 -->
        <picture-library :show="showImg" @close="showImg = false" @select="selectImg"> </picture-library>
    </div>

    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, shallowRef, reactive, onBeforeUnmount } from "vue"
import { useRouter, useRoute } from "vue-router"
import { UploadFilled, CloseBold, ArrowRight, Search, Plus, Edit, Minus } from "@element-plus/icons-vue"
import draggable from "vuedraggable"
import PictureLibrary from "@components/PictureLibrary.vue"
import GoBack from "@components/GoBack.vue"
import BaseSteps from "@components/BaseSteps.vue"
import "@wangeditor/editor/dist/css/style.css"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import UploadVideo from "@mixins/upload-video"

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

let gid = route.query.gid || ""
onMounted(() => {
    gid && getDetail()
    getSupplier()
})

function getDetail() {
    proxy.$axios
        .get("product/update", {
            params: {
                product_id: gid,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                // 第一步，基本信息
                userLevel.value = result.user_grade
                leave_list.value = result.product_levels
                ruleOneForm.comm_id = result.product_common_id
                ruleOneForm.cate_id = result.cate_id
                ruleOneForm.level_id = result.level_id
                ruleOneForm.product_id = result.product_id
                ruleOneForm.supplier_id = result.supplier ? result.supplier.supplier_id : ""
                ruleOneForm.supplier_name = result.supplier ? result.supplier.title : ""
                ruleOneForm.supplier_id && getGoods()

                // 商品主图
                if (result.have_photo == 1) {
                    let imgarrs = [],
                        img_pre = []
                    result.photo_list.forEach((item) => {
                        imgarrs.push(item.photo)
                        img_pre.push(proxy.imgUrl + item.photo)
                    })
                    ruleOneForm.img_paths = imgarrs
                    srcList.value = img_pre
                }
                // 商品属性
                if (result.have_attr == 1) {
                    ruleOneForm.good_attr_id = result.attr_value_ids
                    let names = []
                    result.attr_list.forEach((item) => {
                        names.push(item.attr_value[0].attr_value_name)
                    })
                    ruleOneForm.good_attr_name = names.toString()
                }
                getAttr()
                // 第二步，扩展信息
                ruleTwoForm.supplier_price = result.cost_price
                ruleTwoForm.stock = result.sku
                ruleTwoForm.keywords = result.keywords
                ruleTwoForm.codes = result.sku_code

                ruleTwoForm.dls_rebate = String(result.agent_status) // 是否开启非区域返佣
                ruleTwoForm.large_group = result.one_award
                ruleTwoForm.middle_group = result.two_award
                ruleTwoForm.small_group = result.three_award

                ruleTwoForm.flat_level = result.level_one_award // 一级平级返佣
                ruleTwoForm.flat_level_two = result.level_two_award // 二级平级返佣
                ruleTwoForm.flat_level_three = result.level_three_award // 三级平级返佣
                ruleTwoForm.exceed_level = result.leapfrog_award // 越级返佣

                ruleTwoForm.dls_area_rebate = String(result.partner_status) // 是否开启区域返佣
                ruleTwoForm.pro_area = result.province_award // 省级返佣比例
                ruleTwoForm.city_area = result.city_award
                ruleTwoForm.district_area = result.district_award

                ruleTwoForm.sale = result.base_sales
                ruleTwoForm.sort = result.order_by

                goodObj.value.product_img = result.product_img
                valueHtml.value = result.content.replace(/<img [^>]*src=['"]/g, `<img src="${proxy.imgUrl}`) // 往图片追加根域名和'/'
                if (result.have_video == 1) {
                    videoList.value.push(result.video)
                }
                objs.value = result
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 步骤
 * @param {Number} stepActive 表示当前步骤
 * @param {Number} steps 0表示第一步，依次类推
 */
const stepActive = ref(0)
const stepArr = ref([
    {
        text: "基本信息",
        steps: 0,
    },
    {
        text: "扩展信息",
        steps: 1,
    },
    {
        text: "商品详情",
        steps: 2,
    },
])
const clickCancel = () => {
    router.push("/Goods/GoodsList")
}
const clickPrev = () => {
    if (stepActive.value === 0) return
    stepActive.value--
}

/**
 * 第一步，添加基本信息
 * @param {Boolean} form_loading 按钮状态
 * @param {Array} ruleOneRef 表单规则
 * @param {Object} ruleOneForm  表单字段
 * @param {Object} ruleOneCheck  表单提示
 */
const form_loading = ref(false)
const ruleOneRef = ref(null)
const ruleOneForm = reactive({
    // tag_radio_type: 0,
    supplier_id: "",
    supplier_name: "",
    product_id: "",
    comm_id: "",
    cate_id: "",
    img_paths: [],
    good_attr_id: [],
    good_attr_name: "",
    level_id: "",
})
const ruleOneCheck = reactive({
    supplier_name: [{ required: true, message: "请选择供应商", trigger: "change" }],
    comm_id: [{ required: true, message: "请选择商品", trigger: "change" }],
    img_paths: [{ type: "array", required: true, message: "请选择商品主图", trigger: "change" }],
    level_id: [{ required: true, message: "请选择商品等级", trigger: "change" }],
    // tag_radio_type: [{ required: true, message: "请选择商品标签", trigger: "change" }],
    // good_attr_name: [{ required: true, message: "请选择商品属性", trigger: "blur" }],
})
// 第一步的下一步
const submitOneForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            stepActive.value = 1
            getPriceRule()
        }
    })
}

/**
 * 第二步，添加扩展信息
 * @param {Array} ruleTwoRef 表单规则
 * @param {Object} ruleTwoForm  表单字段
 * @param {Object} ruleTwoCheck  表单提示
 */
const ruleTwoRef = ref(null)
const ruleTwoForm = reactive({
    supplier_price: "",
    stock: "",
    keywords: "",
    codes: "",
    dls_rebate: "1", // 非区域代理商返佣[0:关闭,1:开启]
    large_group: "0", // 一级代理返佣比例
    middle_group: "0",
    small_group: "0",
    flat_level: "0", // 一级平级返佣
    flat_level_two: "0", // 二级平级返佣
    flat_level_three: "0", // 三级平级返佣
    exceed_level: "0", // 越级返佣
    dls_area_rebate: "1", // 区域代理返佣[0:关闭,1:开启]
    pro_area: "0", // 省级
    city_area: "0", // 市级
    district_area: "0", // 县区
    sale: 0,
    sort: "100",
    price: "",
})
const ruleTwoCheck = reactive({
    supplier_price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
    price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    // keywords: [{ required: true, message: "请输入关键词", trigger: "blur" }],
    sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
})
// 第二步的下一步
const submitTwoForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            stepActive.value = 2
        }
    })
}

/**
 * 第三步，富文本及确认保存
 * @param {Function} handleConfirm 保存
 */
const handleConfirm = () => {
    let new_word = ruleTwoForm.keywords
    let end_word = new_word.substring(ruleTwoForm.keywords.length - 1)
    if (end_word === "，") {
        proxy.$message({ message: "关键词不能以中文的“，”隔开，请修改成英文状态下的“,”", type: "warning" })
        return
    }
    if (end_word === ",") {
        new_word = ruleTwoForm.keywords.substring(0, ruleTwoForm.keywords.length - 1)
    }
    let htmls = "",
        levels = []
    if (valueHtml.value) {
        htmls = valueHtml.value.replace(/\bhttps?:\/\/(.*?)\/+/gi, "") // 去除图片根域名以及根域名后面的'/'
    }

    userLevel.value.map((item) => {
        levels.push({
            grade_id: item.grade_id,
            discount: item.discount ? item.discount : 0,
        })
    })

    form_loading.value = true
    let data = {
        product_id: ruleOneForm.product_id,
        product_common_id: ruleOneForm.comm_id,
        level_id: ruleOneForm.level_id,
        video: videoList.value.toString(),
        photos: ruleOneForm.img_paths,
        attr: ruleOneForm.good_attr_id,
        supplier_id: ruleOneForm.supplier_id,
        cost_price: ruleTwoForm.supplier_price,
        sku: ruleTwoForm.stock,
        sku_code: ruleTwoForm.codes,
        keywords: new_word == null ? "" : new_word,
        base_sales: ruleTwoForm.sale,
        user_grade: levels,
        order_by: ruleTwoForm.sort,
        agent_status: ruleTwoForm.dls_rebate, // 非区域返佣[0:关闭,1:开启]
        one_award: ruleTwoForm.large_group ? ruleTwoForm.large_group : 0, // 一级代理返佣比例
        two_award: ruleTwoForm.middle_group ? ruleTwoForm.middle_group : 0,
        three_award: ruleTwoForm.small_group ? ruleTwoForm.small_group : 0,
        level_one_award: ruleTwoForm.flat_level ? ruleTwoForm.flat_level : 0, // 一级平级返佣比例
        level_two_award: ruleTwoForm.flat_level_two ? ruleTwoForm.flat_level_two : 0, // 一级平级返佣比例
        level_three_award: ruleTwoForm.flat_level_three ? ruleTwoForm.flat_level_three : 0, // 三级平级返佣比例
        leapfrog_award: ruleTwoForm.exceed_level ? ruleTwoForm.exceed_level : 0, // 越级返佣比例
        partner_status: ruleTwoForm.dls_area_rebate, // 区域代理商返佣[0:关闭,1:开启]
        province_award: ruleTwoForm.pro_area ? ruleTwoForm.pro_area : 0, // 省级返佣比例
        city_award: ruleTwoForm.city_area ? ruleTwoForm.city_area : 0, // 市级返佣比例
        district_award: ruleTwoForm.district_area ? ruleTwoForm.district_area : 0, // 县级返佣比例
        content: htmls,
    }
    proxy.$axios
        .post("product/update", data)
        .then((res) => {
            form_loading.value = false
            if (res.data.code == 0) {
                proxy.$message({ message: "编辑成功", type: "success" })
                // router.push("/Goods/GoodsList")
                router.back(-1)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            form_loading.value = false
        })
}

/**
 * 会员等级及价格设置
 */
const userLevel = ref([])
const showLevel = ref(false)
// function getUserLevel() {
//     proxy.$axios
//         .get("product/userGrade")
//         .then((res) => {
//             if (res.data.code == 0) {
//                 let result = res.data.data
//                 result.map((item) => {
//                     item.discount = ""
//                 })
//                 userLevel.value = result
//                 getPriceRule()
//             } else {
//                 proxy.$message({message:res.data.msg,type:"error"})
//             }
//         })
//         .catch((err) => {})
// }

/**
 * 获取零售价计算规则
 */
const pricesArr = ref([])
const inputPrice = (val) => {
    for (let i = 0; i < pricesArr.value.length; i++) {
        if (Number(val) >= Number(pricesArr.value[i].product_amount)) {
            ruleTwoForm.price = Number(ruleTwoForm.supplier_price) + Number(pricesArr.value[i].price)
            return
        }
    }
}
function getPriceRule() {
    proxy.$axios
        .get("product/productPrice")
        .then((res) => {
            if (res.data.code == 0) {
                pricesArr.value = res.data.data
                inputPrice(ruleTwoForm.supplier_price)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 选择商品和删除操作
 * @param {String} good_name 搜索字段
 * @param {Boolean} search_btn 搜索按钮状态
 * @param {Boolean} table_loading 表格加载
 * @param {Boolean} dialogSupplier 弹窗状态
 * @param {Number} good_page 页码
 * @param {Number} good_total 总数
 * @param {Array} goods 标签数组
 * @param {Array} leave_list 等级数组
 */
const search_btn = ref(false)
const table_loading = ref(true)
const dialogGoods = ref(false)
const good_page = ref(1)
const good_total = ref(0)
const good_name = ref("")
const goods = ref([])
const goodObj = ref({})
const leave_list = ref([])
watch(good_page, (val) => {
    goods.value = []
    getGoods()
})
const goodSearch = () => {
    search_btn.value = true
    good_page.value = 1
    good_total.value = 0
    goods.value = []
    getGoods()
}
const selectGoods = (row) => {
    dialogGoods.value = false
    ruleOneForm.comm_id = row.product_common_id
    ruleOneForm.cate_id = row.cate_id
    goodObj.value = row
    if (Array.isArray(row.product_levels) && row.product_levels.length == 0) {
        proxy.$alert("未授权商品等级", "温馨提示", {
            confirmButtonText: "确定",
            callback: (action) => {
                router.push("/Goods/GoodsList")
            },
        })
        return
    }
    leave_list.value = row.product_levels
    getAttr()
}
const closeGoods = () => {
    good_name.value = ""
    dialogGoods.value = false
}
const delGood = () => {
    ruleOneForm.comm_id = ""
    ruleOneForm.cate_id = ""
    ruleOneForm.good_attr_id = []
    ruleOneForm.good_attr_name = ""
    goodObj.value = {}
}
function getGoods() {
    table_loading.value = true
    proxy.$axios
        .get("product/productCom", {
            params: {
                page: good_page.value,
                limit: 6,
                supplier_id: ruleOneForm.supplier_id,
                so: good_name.value,
            },
        })
        .then((res) => {
            table_loading.value = false
            search_btn.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                good_total.value = res.data.count
                goods.value = result
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            search_btn.value = false
            table_loading.value = false
        })
}

/**
 * 上传视频
 * @param {Object} uploadRef upload ref
 * @param {Function} delVideo 删除
 */
const { videoList, videoLoading, actionUrl, handleRemove, handleExceed, fileChange, uploadVideo, beforeAvatarUpload } = UploadVideo()
const uploadRef = ref(null)
const delVideo = () => {
    videoList.value = []
}

/**
 * 选择商品属性
 * @param {Boolean} drawerAttr 属性弹窗
 * @param {String} attr_name 属性值
 * @param {Array} attrs 标签数组
 */
const drawerAttr = ref(false)
const attrs = ref([])
const clickDrawAttr = () => {
    if (ruleOneForm.comm_id == "") {
        proxy.$message({ message: "请先选择商品", type: "warning" })
        return
    }
    drawerAttr.value = true
}
const clickAttr = (pitem, sub_index, sub) => {
    // 属性值多选[0:停用,1:启用]
    if (pitem.is_multiple == 0) {
        pitem.attr_value.map((item) => {
            item.is_select = false
        })
    }
    pitem.attr_value[sub_index].is_select = !sub.is_select
}
// 获取属性值选中状态
const getAttrStatus = (arrs) => {
    let flag = false
    for (let j = 0; j < arrs.length; j++) {
        if (arrs[j].is_select) {
            flag = true
        }
    }
    return flag
}
const confirmAttr = () => {
    let ids = [],
        text = []
    for (let i = 0, len = attrs.value.length; i < len; i++) {
        let subs = attrs.value[i].attr_value
        for (let j = 0, len = subs.length; j < len; j++) {
            let flag = getAttrStatus(subs) // 获取属性值选中状态
            if (attrs.value[i].is_necessary == 1 && !flag) {
                // is_necessary-属性值必选[0:停用,1:启用]
                proxy.$message({ message: `${attrs.value[i].attr_name}属性为必选`, type: "warning" })
                return
            }
            if (subs[j].is_select) {
                ids.push(subs[j].attr_value_id)
                text.push(subs[j].attr_value_name)
            }
        }
    }
    // if (ids.length < attrs.value.length) {
    //     proxy.$message({ message: "请完善剩下的属性", type: "warning" })
    //     return
    // }
    if (ids.length > 0) {
        ruleOneForm.good_attr_id = ids
        ruleOneForm.good_attr_name = text.toString()
    }
    drawerAttr.value = false
}
const resetAttr = () => {
    for (let i = 0, len = attrs.value.length; i < len; i++) {
        let subs = attrs.value[i].attr_value
        for (let j = 0, len = subs.length; j < len; j++) {
            subs[j].is_select = false
        }
    }
    ruleOneForm.good_attr_id = []
    ruleOneForm.good_attr_name = ""
}
const closeDeawer = () => {
    drawerAttr.value = false
}
function getAttr() {
    table_loading.value = true
    proxy.$axios
        .get("product/attr", {
            params: {
                cate_id: ruleOneForm.cate_id,
            },
        })
        .then((res) => {
            table_loading.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                if (ruleOneForm.good_attr_id.length > 0) {
                    ruleOneForm.good_attr_id.forEach((item) => {
                        result.forEach((sub) => {
                            let index = sub.attr_value.findIndex((a) => a.attr_value_id === item)
                            index > -1 && (sub.attr_value[index].is_select = true)
                        })
                    })
                }
                attrs.value = result
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            table_loading.value = false
        })
}

/**
 * 选择供应商
 * @param {String} supp_name 搜索供应商字段
 * @param {Boolean} dialogSupplier 弹窗状态
 * @param {Number} supp_page 页码
 * @param {Number} supp_total 总数
 * @param {Array} suppliers 标签数组
 */
const dialogSupplier = ref(false)
const supp_page = ref(1)
const supp_total = ref(0)
const supp_name = ref("")
const suppliers = ref([])
watch(supp_page, (val) => {
    // 跳转第几页
    suppliers.value = []
    getSupplier()
})
const suppSearch = () => {
    search_btn.value = true
    supp_page.value = 1
    supp_total.value = 0
    suppliers.value = []
    getSupplier()
}
const selectSupp = (row) => {
    dialogSupplier.value = false
    ruleOneForm.supplier_id = row.supplier_id
    ruleOneForm.supplier_name = row.title
    setTimeout(() => {
        ruleOneForm.comm_id = ""
        ruleOneForm.img_paths = []
        ruleOneForm.level_id = ""
        ruleOneForm.good_attr_id = []
        ruleOneForm.good_attr_name = ""
        goods.value = []
        goodObj.value = {}
        good_page.value = 1
        good_total.value = 0
        getGoods()
    }, 50)
}
const closeSupp = () => {
    supp_name.value = ""
    dialogSupplier.value = false
}
function getSupplier() {
    table_loading.value = true
    proxy.$axios
        .get("product/supplier", {
            params: {
                page: supp_page.value,
                limit: 6,
                so: supp_name.value,
            },
        })
        .then((res) => {
            table_loading.value = false
            search_btn.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                supp_total.value = res.data.count
                suppliers.value = result
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            search_btn.value = false
            table_loading.value = false
        })
}

/**
 * 添加图片
 * @property {Boolean} showImg 显示图片库
 * @property {Function} selectImg 选择图片
 */
const showImg = ref(false)
const srcList = ref([])
const selectImg = (val) => {
    showImg.value = false
    for (let i = 0; i < val.length; i++) {
        ruleOneForm.img_paths.push(val[i].photo)
        srcList.value.push(proxy.imgUrl + val[i].photo)
    }
}
const delImg = (index) => {
    ruleOneForm.img_paths.splice(index, 1)
    srcList.value.splice(index, 1)
}

/**
 * 标签类型
 * @param {String} tag_type 标签值
 * @param {Array} tags 标签数组
 */
// const tags = ref([
//     {
//         type: 0,
//         names: "无标签",
//     },
//     {
//         type: 1,
//         names: "特惠",
//     },
//     {
//         type: 2,
//         names: "新品",
//     },
//     {
//         type: 3,
//         names: "视频",
//     },
// ])
// function getTags() {
//     proxy.$axios
//         .get("")
//         .then((res) => {
//             if (res.data.code == 0) {
//                 tags.value = res.data.data
//             } else {
//                 proxy.$message({message:res.data.msg,type:"error"})
//             }
//         })
//         .catch((err) => {})
// }

/**
 * 富文本编辑器
 * @param {Object} editorConfig 编辑器配置
 * @param {String} valueHtml 输入内容
 * @param {Object} toolbarConfig 工具栏配置
 * @param {Function} createEditor 创建编辑器
 * @param {Function} createToolbar 创建工具栏
 * @param {Function} handleChange 编辑器内容变化
 */
const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
const valueHtml = ref("") // 内容 HTML
const toolbarConfig = {
    // 排除不需要的菜单
    excludeKeys: ["insertLink", "insertImage", "editImage", "viewImageLink", "group-video", "emotion", "fullScreen"],
}
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} }
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
editorConfig.MENU_CONF["uploadImage"] = {
    // 自定义上传
    async customUpload(file, insertFn) {
        let data = new FormData()
        data.append("from", "article")
        data.append("image", file)
        proxy.$axios
            .post("upload/image", data)
            .then((res) => {
                if (res.data.code == 0) {
                    let url = proxy.imgUrl + res.data.data.path
                    insertFn(url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
                } else {
                    proxy.$message({ message: res.data.msg, type: "error" })
                }
            })
            .catch((err) => {})
    },
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    ruleOneRef.value = null

    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
</script>
<script>
export default {
    name: "GoodsListEdit",
}
</script>

<style lang="less" scoped>
.table-lr {
    .table-lr__img {
        width: 40px;
        height: 40px;
    }
    .supp-logo {
        border-radius: 50%;
        overflow: hidden;
    }
    .table-lr__right {
        min-height: 40px;
    }
}
.vip-price {
    margin-top: @margin-md;
    clear: both;
    width: 100%;
    .vip-level {
        width: 530px;
        background-color: @gray-1;
        min-height: 240px;
        padding: @padding-lg @padding-mdl @padding-sm;
        .vip-level__item {
            display: flex;
            margin-bottom: @margin-md;
            .vip-level__text {
                flex: none;
                font-size: @font-size-md;
                color: @gray-8;
                min-width: 100px;
                text-align: right;
                padding-right: 20px;
            }
            .vip-level__right {
                flex: 1;
                :deep(.el-input) {
                    width: 200px;
                }
                .vip-level__right-icon {
                    margin-right: @margin-xs;
                    font-size: 16px;
                }
                .vip-level__right-unit {
                    margin-left: @margin-xs;
                }
            }
        }
    }
}
.step-h3 {
    font-size: 16px;
    font-weight: bold;
    color: #555;
    margin: @margin-lg 0px;
    span {
        font-size: 13px;
        font-weight: 600;
    }
}

.form-item__char {
    color: @gray-7;
    font-size: @font-size-md;
    margin-left: @margin-sm;
}
.form-item__btn {
    margin-left: @padding-lg;
}

.foot-btn {
    .el-button {
        margin-left: 18px;
    }
}
.video-box {
    width: 300px;
    height: 200px;
    margin-right: @margin-md;
    position: relative;
    video {
        width: 100%;
        height: 100%;
    }
    .video-del {
        position: absolute;
        top: 5px;
        right: -8px;
        z-index: 11;
        width: 22px;
        height: 22px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        overflow: hidden;
        background-color: @themes;
        cursor: pointer;
    }
}

.img-selects {
    :deep(.el-image) {
        img {
            cursor: move;
        }
    }
}

.prize-upload {
    :deep(.el-upload--picture-card) {
        width: 100px;
        height: 100px;
        line-height: 100px;
    }

    :deep(.el-upload-list__item) {
        width: 100px;
        height: 100px;
    }
}
.attr-box {
    margin-bottom: @margin-md;
    .attr-title {
        font-size: @font-size-lg;
        color: #000;
        margin-bottom: @margin-md;
    }
    .attr-sub {
        display: flex;
        flex-flow: row wrap;
        .attr-label {
            flex: none;
            padding: 6px 12px;
            color: @gray-8;
            font-size: @font-size-md;
            margin: 0px @margin-sm @margin-sm 0;
            border: 1px solid #ededed;
            border-radius: 10px;
            cursor: pointer;
        }
        .attr-active {
            background-color: @themes;
            color: #fff;
            border: 1px solid @themes;
        }
    }
}

.editor-box {
    border: 1px solid #ccc;
    border-radius: 2px;
}
</style>
